#include"list.h"
#include"freq.h"
#include<stdlib.h>

ListNode * ListNode_create(TreeNode * tn){

    ListNode * ln = malloc(sizeof(ListNode));
    ln->tnptr = tn;
    ln->next = NULL;

    return ln;
}

// head可以为空
// ln必须不为空
// ln->next必须为空
ListNode * List_insert(ListNode * head,ListNode * ln,int mode){

    if(NULL == ln){

        printf("ERROR!!! ln is NULL.\n");
        return NULL;
    }
    if(NULL!=ln->next){

        printf("ERROR!!! ln->next is not NULL.\n");
    }
    if(NULL == head){

        return ln;
    }
    if(STACK == mode){

        ln->next = head;
        return ln;
    }
    if(QUEUE == mode){

        head->next = List_insert(head->next,ln,QUEUE);
        return head;
    }
    // 在增序中插入
    int freq1 = (head->tnptr)->freq;
    int freq2 = (ln->tnptr)->freq;
    if(freq1 > freq2){

        ln->next = head;
        return ln;
    }
    head->next = List_insert(head->next,ln,mode);
    return head;
}

// 频率必须被存储
ListNode * List_build(CharFreq * frequencies){

    int index = 0;
    // 找到第一个
    while(index < NUMLETTER && frequencies[index].freq!=0){

        index++;
    }
    // 没有字符出现
    if(index == NUMLETTER){

        return NULL;
    }
    // 构建链表并返回
    ListNode * head = NULL;
    while(index < NUMLETTER){

        TreeNode * tn = TreeNode_create(frequencies[index].value,frequencies[index].freq);
        ListNode * node = ListNode_create(tn);

        head = List_insert(head,node,SORTED);
        index++;
    }
    return head;
}

void List_print(ListNode * head){

    //输出节点的树结构
    // head->tnptr
}